package com.advanced.component;

import com.advanced.strategy.CreateCodePrefixDbConfig;
import com.advanced.strategy.CreateCodeSuffixTableConfig;
import com.advanced.util.CommonUtil;
import org.springframework.stereotype.Component;

/**
 * 生成partitionKey，其实该过程也是生成短链码的过程之一
 */
@Component
public class PratitionKeyComponent {

    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public String createPratition(String param){
        // 做 murmurHash计算
        Long murmurHash32 = CommonUtil.murmurHash32(param);

        // 转62进制
        String code = this.encodingTo62(murmurHash32);

        // 拼装库前缀 与 表后缀
        String partitionCode = CreateCodePrefixDbConfig.getPartitionDbPrefix() + code + CreateCodeSuffixTableConfig.getPartitionTableSuffix();
        return partitionCode;
    }

    /**
     * 10进制转换成62进制
     * @param murmurHash32 hash值
     * @return
     */
    private String encodingTo62(Long murmurHash32){

        // StringBuffer线程安全，StringBuilder线程不安全
        StringBuffer stringBuffer = new StringBuffer();
        do {
            int i = (int) (murmurHash32 % 62);
            stringBuffer.append(CHARS.charAt(i));
            murmurHash32 /= 62;
            // num = num/ 62;
        }while (murmurHash32 > 0);
        String value = stringBuffer.reverse().toString();
        return value;
    }
}
